Ext.define('YXMES.sres.controller.DeviceMaintainSetupController', {
	extend : 'Ext.app.Controller',
	refs : [ {
		selector : 'sres_devicemaintainsetup',
		ref : 'sresdevicemaintainsetup'
	} ],
	requires : [ 'YXMES.sres.store.ResourceStore', 'YXMES.sres.store.ResTypeStore', 'YXMES.sres.store.AllMaintainStore', 'YXMES.sres.store.DeviceMaintainStore' ],
	stores : [],
	models : [],
	views : [ 'YXMES.sres.view.DeviceMaintainSetupView' ],
	subcontrollers : [  ],
	_init : false,
	init : function() {
		if (this._init)
			return;
		this._init = true;
		this.control({
			'sres_devicemaintainsetup' : {
				afterrender : function() {
					return this.handle(this.onAfterrender, arguments);
				},
				destroy : function() {
					return this.handle(this.onDestroy, arguments);
				}
			},
			'sres_devicemaintainsetup #btnSearch' : {
				click : function() {
					return this.handle(this.onBtnSearchClick, arguments);
				}
			},
			'sres_devicemaintainsetup #btnReset' : {
				click : function() {
					return this.handle(this.onBtnResetClick, arguments);
				}
			},
			'sres_devicemaintainsetup #grdDeviceResource' : {
				select : function() {
					return this.handle(this.onGrdDeviceResourceSelect, arguments);
				}
			},
			'sres_devicemaintainsetup #txtMaintainCond' : {
				specialkey : function() {
					return this.handle(this.onTxtMaintainCondSpecialkey, arguments);
				}
			},
			'sres_devicemaintainsetup #btnGoRight' : {
				click : function() {
					return this.handle(this.onBtnGoRightClick, arguments);
				}
			},
			'sres_devicemaintainsetup #btnGoLeft' : {
				click : function() {
					return this.handle(this.onBtnGoLeftClick, arguments);
				}
			},
			'sres_devicemaintainsetup #btnSave' : {
				click : function() {
					return this.handle(this.onBtnSaveClick, arguments);
				}
			}
		});
		if (!Ext.isEmpty(this.subcontrollers)) {
			Ext.each(this.subcontrollers, function(name) {
				this.getController(name).init();
			}, this);
		}
		// User definied init
	},
	mainView : undefined,
	getMainView : function() {
		return this.mainView;
	},
	getScopeView : function() {
		return this.getMainView().scopeView || {};
	},
	getInput : function() {
		return this.getScopeView().input || {};
	},
	setInput : function(data) {
		this.getMainView().input = data;
	},
	getOutput : function() {
		return this.getMainView().output || {};
	},
	setOutput : function(data) {
		this.getScopeView().output = data;
	},
	handle : function(func, args) {
		var item = args && args.length > 0 && Ext.typeOf(args[0]) === 'object' ? args[0] : undefined;
		if (item) {
			try {
				this.mainView = (item.xtype == 'sres_devicemaintainsetup' ? item : item.up('sres_devicemaintainsetup'));
			} catch(e) {
			}
		}
		try {
			return func.apply(this, args);
		} finally {
		}
	},
	getItem : function(itemId) {
		return this.getMainView().down('#' + itemId);
	},
	getStore : function(name) {
		if (name == 'ResourceStore')
			return this.getMainView().SresViewDeviceResourceServiceStore;
		if (name == 'ResTypeStore')
			return this.getMainView().BasViewCommonDataSetupDetailServiceStore;
		if (name == 'AllMaintainStore')
			return this.getMainView().SresViewMaintainItemsWithoutDeviceServiceStore;
		if (name == 'DeviceMaintainStore')
			return this.getMainView().SresViewDeviceMaintainItemDetailServiceStore;
		return undefined;
	},
	bind : function(view) {
		view = (view ? view : this.getMainView());
		view.SresViewDeviceResourceServiceStore = Ext.create('YXMES.sres.store.ResourceStore', {
			pageSize : 30
		});
		view.BasViewCommonDataSetupDetailServiceStore = Ext.create('YXMES.sres.store.ResTypeStore', {
			pageSize : 30
		});
		view.SresViewMaintainItemsWithoutDeviceServiceStore = Ext.create('YXMES.sres.store.AllMaintainStore', {
			pageSize : 30
		});
		view.SresViewDeviceMaintainItemDetailServiceStore = Ext.create('YXMES.sres.store.DeviceMaintainStore', {
			pageSize : 30
		});
		view.down('#grdDeviceResource').reconfigure(view.SresViewDeviceResourceServiceStore);
		view.down('#bar4').bindStore(view.SresViewDeviceResourceServiceStore);
		view.down('#cmbResType').bindStore(view.BasViewCommonDataSetupDetailServiceStore);
		view.down('#grdAllMtnItem').reconfigure(view.SresViewMaintainItemsWithoutDeviceServiceStore);
		view.down('#bar8').bindStore(view.SresViewMaintainItemsWithoutDeviceServiceStore);
		view.down('#grdDeviceMtnItem').reconfigure(view.SresViewDeviceMaintainItemDetailServiceStore);
		view.down('#bar15').bindStore(view.SresViewDeviceMaintainItemDetailServiceStore);
		view.SresViewDeviceResourceServiceStore.on('load', function(store, records, successful, eOpts) {
			this.getStore('AllMaintainStore').removeAll();
			this.getStore('DeviceMaintainStore').removeAll();
		}, this);
	},
	onAfterrender : function(view, eOpts) {
		this.bind();
		// User defined afterrender
		this.loadResTypeStore({
		    groupName: 'RES_TYPE'
		});
	},
	onDestroy : function(view, eOpts) {
		// User defined destory
		var view = this.getMainView();
		if (view.SresViewDeviceResourceServiceStore) {
			view.SresViewDeviceResourceServiceStore.destroyStore();
			view.SresViewDeviceResourceServiceStore = undefined;
		}
		if (view.BasViewCommonDataSetupDetailServiceStore) {
			view.BasViewCommonDataSetupDetailServiceStore.destroyStore();
			view.BasViewCommonDataSetupDetailServiceStore = undefined;
		}
		if (view.SresViewMaintainItemsWithoutDeviceServiceStore) {
			view.SresViewMaintainItemsWithoutDeviceServiceStore.destroyStore();
			view.SresViewMaintainItemsWithoutDeviceServiceStore = undefined;
		}
		if (view.SresViewDeviceMaintainItemDetailServiceStore) {
			view.SresViewDeviceMaintainItemDetailServiceStore.destroyStore();
			view.SresViewDeviceMaintainItemDetailServiceStore = undefined;
		}
		if (this.getMainView().input)
			this.getMainView().input = undefined;
		if (this.getMainView().output)
			this.getMainView().output = undefined;
	},
	onBtnSearchClick : function(button, e, eOpts) {
		this.loadResourceStore(this.getItem('frmSearch').getValues());
	},
	onBtnResetClick : function(button, e, eOpts) {
		this.getItem('frmSearch').getForm().reset();
	},
	onGrdDeviceResourceSelect : function(selModel, record, index, eOpts) {
		this.loadAllMaintainStore({
		    resId: record.get('resId')
		});
		
		this.loadDeviceMaintainStore({
		    resId: record.get('resId')
		});
	},
	onTxtMaintainCondSpecialkey : function(textfield, e, eOpts) {
		if (e.getKey() == e.KEY_ENTER) {
		    var cond = {
		        cond: textfield.getValue(),
		        resId: null
		    };
		
		    if (this.getItem('grdDeviceResource').getSelectionModel().hasSelection()) {
		        cond.resId = this.getItem('grdDeviceResource').getSelectionModel().getSelection()[0];
		    }
		
		    this.loadAllMaintainStore(cond);
		}
	},
	onBtnGoRightClick : function(button, e, eOpts) {
		if (this.getItem('grdAllMtnItem').getSelectionModel().hasSelection() && this.getItem('grdDeviceResource').getSelectionModel().hasSelection()) {
		    var resRcd = this.getItem('grdDeviceResource').getSelectionModel().getSelection()[0];
		    var rcd = this.getItem('grdAllMtnItem').getSelectionModel().getSelection()[0];
		    var me = this;
		    YX.ZbusRpc.request({
		        module: 'SresSaveDeviceMaintainDetailService',
		        params: {
		            detailList: [{
		                resId: resRcd.get('resId'),
		                itemCode: rcd.get('itemCode')
		            }]
		        },
		        showSuccess: false,
		        success: function() {
		            me.getStore('AllMaintainStore').remove(rcd);
		            me.loadDeviceMaintainStore({
		                resId: resRcd.get('resId')
		            });
		        }
		    });
		}
	},
	onBtnGoLeftClick : function(button, e, eOpts) {
		if (this.getItem('grdDeviceMtnItem').getSelectionModel().hasSelection()) {
		    var rcd = this.getItem('grdDeviceMtnItem').getSelectionModel().getSelection()[0];
		    var me = this;
		    YX.ZbusRpc.request({
		        module: 'SresSaveDeviceMaintainDetailService',
		        params: {
		            detailList: [{
		                resId: rcd.get('resId'),
		                itemCode: rcd.get('itemCode'),
		                status: 'D'
		            }]
		        },
		        showSuccess: false,
		        success: function() {
		            me.getStore('DeviceMaintainStore').remove(rcd);
		            me.getStore('AllMaintainStore').reload();
		        }
		    });
		}
	},
	onBtnSaveClick : function(button, e, eOpts) {
		var st = this.getStore('DeviceMaintainStore');
		if (st.getCount() === 0 && Ext.isEmpty(st.getModifiedRecords())) {
		    Ext.Msg.show({
		        title: T.label.save,
		        msg: T.msg.no_data_can_be_saved,
		        icon: Ext.Msg.ERROR,
		        buttons: Ext.Msg.OK
		    });
		
		    return;
		}
		
		var me = this;
		var vResId = this.getItem('grdDeviceResource').getSelectionModel().getSelection()[0].get('resId');
		var dtl = [];
		Ext.each(st.getModifiedRecords(),
		function(item) {
		    var data = Ext.clone(item.data);
		    data.resId = vResId;
		    if (!data.noticeFlag || data.noticeFlag === "false") {
		        data.noticeFlag = 'N';
		    } else {
		        data.noticeFlag = 'Y';
		    }
		    dtl.push(data);
		});
		
		Ext.Msg.show({
		    title: button.getText(),
		    msg: T.msg.are_you_sure_to_delete_data,
		    icon: Ext.Msg.QUESTION,
		    buttons: Ext.Msg.YESNO,
		    fn: function(btnId) {
		        if ('yes' == btnId) {
		            button.setDisabled(true);
		
		            YX.ZbusRpc.request({
		                module: 'SresSaveDeviceMaintainDetailService',
		                params: {
		                    detailList: dtl
		                },
		                showSuccess: true,
		                callback: function() {
		                    button.setDisabled(false);
		                },
		                success: function() {
		                    st.commitChanges();
		                }
		            })
		        }
		    }
		});
	},
	loadResourceStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('ResourceStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		store.loadPage(1, options);
	},
	loadResTypeStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('ResTypeStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		store.loadPage(1, options);
	},
	loadAllMaintainStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('AllMaintainStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		store.loadPage(1, options);
	},
	loadDeviceMaintainStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('DeviceMaintainStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		store.loadPage(1, options);
	}
});